<template>
    <div class="padding20">
        <!--面包屑导航区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!--卡片视图-->
        <el-card>
            <!--警告条-->
            <el-alert show-icon :closable="false" title="注意：只允许为第三级分类设置相关参数" type="warning"></el-alert>

            <!--选择分类区域-->
            <el-row>
                <el-col class="marginTop20">
                    <span>选择商品分类：</span>
                    <el-cascader
                        v-model="selectKeys"
                        :options="cateList"
                        :props="slectedCateProps"
                        @change="handleChangeCate"
                        clearable
                    >
                    </el-cascader>
                </el-col>
            </el-row>

            <!--tags页签区-->
            <el-tabs v-model="activeTag" @tab-click="handleClickTag" class="marginTop20">
                <!--动态参数面板-->
                <el-tab-pane label="动态参数" name="many">
                    <el-button :disabled="isBtnDisable" type="primary" class="marginTop20" @click="showAddDialog">添加参数</el-button>
                    <el-table
                        :data="manyTableData"
                        border
                        style="width: 100%">
                        <el-table-column type="expand">
                            <template slot-scope="{row}" width="40px">
                                <el-tag v-for="(item,index) in row.attr_vals"  :key="index" closable @close="handleDelTag(index,row)">{{item}}</el-tag>
                                <el-input
                                    class="input-new-tag"
                                    v-if="row.inputVisible"
                                    v-model="row.inputTagValue"
                                    ref="addTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(row)"
                                    @blur="handleInputConfirm(row)"
                                >
                                </el-input>
                                <el-button v-else  size="small" @click="showTagInput(row)">+ New Tag</el-button>
                            </template> 
                        </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="{row}" width="40px">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditParamDialog(row.attr_id)">编辑</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="delParam(row)">删除</el-button>
                            </template>   
                        </el-table-column>
                    </el-table>

                </el-tab-pane>
                <!--静态属性面板-->
                <el-tab-pane label="静态属性" name="only">
                    <el-button :disabled="isBtnDisable" type="primary" class="marginTop20" @click="showAddDialog">添加属性</el-button>
                    <el-table
                        :data="onlyTableData"
                        border
                        style="width: 100%">
                        <el-table-column type="expand">
                            <template slot-scope="{row}" width="40px">
                                <el-tag v-for="(item,index) in row.attr_vals"  :key="index" closable @close="handleDelTag(index,row)">{{item}}</el-tag>
                                <el-input
                                    class="input-new-tag"
                                    v-if="row.inputVisible"
                                    v-model="row.inputTagValue"
                                    ref="addTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(row)"
                                    @blur="handleInputConfirm(row)"
                                >
                                </el-input>
                                <el-button v-else  size="small" @click="showTagInput(row)">+ New Tag</el-button>
                            </template> 
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="{row}" width="40px">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditParamDialog(row.attr_id)">编辑</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="delParam(row)">删除</el-button>
                            </template>   
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>    

        <!--添加 参数/属性 对话框-->
        <el-dialog
            :title="this.activeTag===`many`?`添加参数`:`添加属性`"
            :visible.sync="showAddDialogVisible"
            width="50%"
            @close="closeAddDialog">
            <!--内容主体区-->
            <el-form :model="addFrom" :rules="addRules" ref="addFromRef" label-width="100px">
                <el-form-item prop="attr_name" :label="this.activeTag===`many`?`动态参数`:`静态属性`">
                    <el-input v-model="addFrom.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <!--底部按钮区-->
            <span slot="footer">
                <el-button @click="closeAddDialog">取 消</el-button>
                <el-button type="primary" @click="handleAddDialogPost">确 定</el-button>
            </span>
        </el-dialog>

        <!--修改 参数/属性 对话框-->
        <el-dialog
            :title="this.activeTag===`many`?`修改参数`:`修改属性`"
            :visible.sync="showEditDialogVisible"
            width="50%"
            @close="closeEditDialog">
            <!--内容主体区-->
            <el-form :model="editFrom" :rules="addRules" ref="editFromRef" label-width="100px">
                <el-form-item prop="attr_name" :label="this.activeTag===`many`?`动态参数`:`静态属性`">
                    <el-input v-model="editFrom.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <!--底部按钮区-->
            <span slot="footer">
                <el-button @click="closeEditDialog">取 消</el-button>
                <el-button type="primary" @click="handleEditDialogPost">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {handleGetCates} from '@/request/cate'
import {handleGetAttrsByCateId,handleAddAttrsByCateId,getAttrByCateIdAndAttrId,editAttr,deleteAttr} from '@/request/params'
export default {
    props: {

    },
    components: {

    },
    data() {
        return {
            cateList:[],
            slectedCateProps:{    //级联选择器配置对象
                value: 'cat_id',
                label: 'cat_name',
                children: 'children'
            },
            selectKeys:[],         //级联选择器选中的数组对象
            activeTag:'many',
            manyTableData:[],
            onlyTableData:[],
            showAddDialogVisible:false, //显示增加对话框
            addFrom: {
               attr_name: '',
               attr_sel:''   //添加类型
            },
            addRules:{
                attr_name: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
            },
            showEditDialogVisible:false,  //显示修改对话框
            editFrom:{}
        };
    },
    computed: {
        //是否禁用添加按钮
        isBtnDisable(){
            return this.selectKeys.length!==3
        },
        //被选中获取三级分类id
        cateId(){
            //如果不是三级分类返回空！
            return this.selectKeys.length===0? null: this.selectKeys[2]
        }
    },
    created() {
        this.getCatesData()
    },
    mounted() {

    },
    watch: {

    },
    methods: {
        //删除tag
        handleDelTag(index,row){
            row.attr_vals.splice(index,1)
            this.handleEditTags(this.cateId,row)
        },
        /*
            数去焦点或者确定键盘  添加动态参数可选项
        */
        async handleInputConfirm(row){
            if(row.inputTagValue.trim().length===0){ //没内容
                row.inputTagValue = ''
                row.inputVisible = false
                return
            }else{    //有内容
                row.attr_vals.push(row.inputTagValue.trim())  //往输入加进去一个
                this.handleEditTags(this.cateId,row)
            }
        },
        async handleEditTags(cateId,row){
            let res =  await editAttr(cateId,row.attr_id,{
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(',')  //转为字符串
                })
                if(res.meta.status!==200){
                    row.inputTagValue = ''
                    row.inputVisible = false
                    return this.$message.error('编辑tag失败！')
                }else{
                    row.inputTagValue = ''
                    row.inputVisible = false
                }
        },
        /*
            显示动态参数可选项输入框
        */
        showTagInput(row){
            row.inputVisible = true
            this.$nextTick(_ => {
                this.$refs.addTagInput.$refs.input.focus();
            });
        },
        /*
            删除
        */
        async delParam(attr){
           let title = this.activeTag=='many'? `动态参数`:`静态属性`
           let delResult = await this.$confirm(`确定删除《${attr.attr_name}》${title}吗?`,'提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            .catch(err=>err)
            // 取消是cancel  确定是confirm
            if(delResult==='confirm'){
                deleteAttr(this.cateId,attr.attr_id)
                .then(res=>{
                    if(res.meta.status!==200){
                        this.$message.error(res.meta.msg)
                    }else{
                        this.$message.success(res.meta.msg)
                        this.handleGetParamsListData()  //刷新数据
                    }
                })
            }
       },
        /*
            显示/关闭 编辑对话框方法
        */
        async showEditParamDialog(attr_id){
            let res = await getAttrByCateIdAndAttrId(this.selectKeys[2],attr_id)  //请求具体参数（属性）信息
            if(res.meta.status!==200){
                return this.$message.error('获取'+this.activeTag=='many'? `动态参数`:`静态属性` + `失败`)
            }else{
                this.showEditDialogVisible = true //打开窗口
                this.editFrom = res.data
            }
        },
        closeEditDialog(){
            this.$refs.editFromRef.resetFields()
            this.editFrom = {}
            this.showEditDialogVisible = false
        },
        // 确定编辑方法
        handleEditDialogPost(){
            this.$refs.editFromRef.validate(async valid=>{
                if(valid){  //校验通过
                    let res = await editAttr(this.cateId,this.editFrom.attr_id,this.editFrom)
                    if(res.meta.status!==200){
                        return this.$message.error('修改'+this.activeTag=='many'? `动态参数`:`静态属性`+'失败')
                    }else{
                        this.closeEditDialog() //关闭窗口
                        this.handleGetParamsListData() //刷数据
                        this.$message.success('修改'+this.activeTag=='many'? `动态参数`:`静态属性`+'成功！')
                    }
                }else{
                  this.$message.error('请完善对应信息')
                }
            })
        },
        /*
            显示/关闭 增加对话框方法
        */
        showAddDialog(){
            this.addFrom.attr_sel = this.activeTag
            this.showAddDialogVisible = true
        },
        closeAddDialog(){
            this.$refs.addFromRef.resetFields()
            this.showAddDialogVisible = false
        },
        /*
            确定添加 属性/参数
        */
       handleAddDialogPost(){
           this.$refs.addFromRef.validate(async valid=>{
                if(valid){  //校验通过
                    let res = await handleAddAttrsByCateId(this.cateId,this.addFrom)
                    if(res.meta.status!==201){
                        return this.$message.error('添加参数失败')
                    }else{
                        this.closeAddDialog() //关闭窗口
                        this.handleGetParamsListData()  //刷新数据
                        this.$message.success('添加成功！')
                    }
                }else{
                  this.$message.error('请完善对应信息')
                }
            })
       },
        /*
            加载级联选择框数据
        */
        async getCatesData(){
            let res =  await handleGetCates(this.queryInfo)
            if(res.meta.status!==200){
                return this.$message.error('获取商品分类列表失败')
            }else{
               this.cateList = res.data
            }
        },
        /*
            监听分类被改变
        */
        async handleChangeCate(){
            this.handleGetParamsListData()
        },
        /*
            点击页签
        */
       handleClickTag(tag){
           console.log(tag.name)
           this.handleGetParamsListData()
       },
       /*
            获取分类对应的参数列表数据
       */
        async handleGetParamsListData(){
           //如果不是三级分类不加载
            if(this.selectKeys.length!==3){
                this.onlyTableData = []
                this.manyTableData = []
                return 
            }
            let res =  await handleGetAttrsByCateId(this.cateId,{sel:this.activeTag})
            if(res.meta.status!==200){
                return this.$message.error('获取分类参数列表失败')
            }else{
               res.data.forEach(item => {
                   if(item.attr_vals && item.attr_vals!==''){
                        item.attr_vals = item.attr_vals.split(',')
                   }else{
                       item.attr_vals = []
                   }

                   //控制增加tag文本框的显示与隐藏
                   item.inputVisible = false
                   item.inputTagValue = ''
               });
               if(this.activeTag==='only'){
                   this.onlyTableData = res.data
               }else{
                   this.manyTableData = res.data
               }
            }
       }
    },
};
</script>

<style scoped lang="less">
.input-new-tag{
    width:100px;
}
</style>
